package com.wangzhixuan.apiController;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.wangzhixuan.commons.base.ApiBaseController;
import com.wangzhixuan.commons.constant.ApiCode;
import com.wangzhixuan.commons.utils.UUIDGenerator;

//@CrossOrigin(origins = "*") 当前版本1.7 会报错，原因版本太低 http://spring.io/guides/gs/rest-service-cors/
@Controller
@RequestMapping("api/resource")
public class FileUploadApiController extends ApiBaseController {

	@RequestMapping(value = "/upload")
	@ResponseBody
	public Object fileUpload(
			@RequestParam("myfiles") CommonsMultipartFile[] myfiles,HttpServletRequest request, HttpServletResponse response)throws Exception {
		for(MultipartFile myfile : myfiles){
        	if(myfile.isEmpty()){  
        		return renderError(ApiCode.CODE_1501, "请选择文件后上传"); 
        	}
        }
		List<String> urlList = saveFiles(myfiles, request);
		System.out.println("返回地址："+urlList);
		return renderSuccess(ApiCode.CODE_200, "上传成功", urlList);
	}

	private List<String> saveFiles(MultipartFile[] myfiles, HttpServletRequest request)
			throws Exception, IOException {
		String pathRoot = getRootPath();
		String filePath = mkdirs(pathRoot);
		new File(filePath).mkdirs();
		List<String> list = new ArrayList<String>();
		for(MultipartFile myfile : myfiles){
			System.out.println(myfile.getOriginalFilename());
			String fileType = myfile.getOriginalFilename().substring(
					myfile.getOriginalFilename().lastIndexOf("."));
			String resId = UUIDGenerator.getUUID();
			String tempfilePath = filePath + resId + fileType;
			myfile.transferTo(new File(pathRoot + tempfilePath));
			list.add(getbaseUrl(request) + tempfilePath);
		}
		return list;
	}

	private String mkdirs(String pathRoot) {
		Date date = new Date();
		StringBuffer path = new StringBuffer();
		path.append(new SimpleDateFormat("yyyy/MM/dd").format(date))
				.append("/");
		File f = new File(pathRoot + path.toString());
		if (!f.exists())
			f.mkdirs();
		return path.toString();
	}
}
